var fs= require("fs")
const path = require('path')

// 递归删除文件夹
function deleteFolder(filePath) {
	const files = []
	if (fs.existsSync(filePath)) {
	  const files = fs.readdirSync(filePath)
	  files.forEach((file) => {
		const nextFilePath = `${filePath}/${file}`
		const states = fs.statSync(nextFilePath)
		if (states.isDirectory()) {
		  //recurse
		  deleteFolder(nextFilePath)
		} else {
		  //delete file
		  fs.unlinkSync(nextFilePath)
		}
	  })
	  fs.rmdirSync(filePath)
	}
  }

// 递归拷贝文件
function copyFile (srcPath, tarPath, filter = []) {
	fs.readdir(srcPath, function (err, files) {
	  console.log(files)
	  if (err === null) {
		files.forEach(function (filename) {
		  let filedir = path.join(srcPath,filename);
		  let filterFlag = filter.some(item => item === filename)
		  if (!filterFlag) {
			fs.stat(filedir, function (errs, stats) {
			  let isFile = stats.isFile()
			  if (isFile) {                                    // 复制文件
				const destPath = path.join(tarPath,filename);
				fs.copyFile(filedir, destPath, (err) =>  { })
			  } else {                                        // 创建文件夹
				let tarFiledir = path.join(tarPath,filename);
				fs.mkdir(tarFiledir,(err) =>  { });
				copyFile(filedir, tarFiledir, filter)                 // 递归
			  }
			})
		  }
		})
	  } else {
		if (err) console.error(err);
	  }
	})
  }

function copyModules() {
	let packageFilePath = 'package.json'
	let privateModulesFilePath = 'src/privateModules'

	// 删除原来的 privateModules 文件夹
	deleteFolder(privateModulesFilePath)

	// 重新创建 privateModules 文件夹
	if (!fs.existsSync(privateModulesFilePath)) {
		fs.mkdirSync(privateModulesFilePath)
	}

	// 读取package.json文件
	let build = fs.readFileSync(packageFilePath, 'utf-8')
	build = JSON.parse(build)
	let privateArr = build.optionalDependencies
	// console.log(' ==== privateArr === ', privateArr)
	if (privateArr) {
		for (let k in privateArr) {
			let srcPath = 'node_modules/' + k + '/src'
			let distPath = privateModulesFilePath + '/' + k 
			if (!fs.existsSync(srcPath)) {
				continue
			}
			if (!fs.existsSync(distPath)) {
				fs.mkdirSync(distPath)
			}
			console.log(' ==== srcPath === ', srcPath)
			copyFile(srcPath, distPath, [])
		}
	}
}

copyModules();